package 二分查找;

/**
 *
 * 二分超找算法只适用于有序数组的选择，它的时间复杂度是O(log n)
 *
 * Created by sult on 2018/8/2.
 */
public class Demo {

    private int[] nums = {1,2,5,7,9,12,20,21,23,24,27,31,35,50,52,58,60,62,66,68,69,70};

    public int index(int num){
        int first = 0;
        int last = nums.length-1;
        while (first<=last) {
            int middle = (first+last)/2;
            if (nums[middle] == num) {
                return middle;
            } else if (nums[middle] > num) {
                last = middle-1;
            } else if (nums[middle] < num) {
                first = middle+1;
            }
        }
        return -1;
    }

    public static void main(String[] args){
        Demo d = new Demo();
        int i=d.index(50);
        System.out.println(i);
    }

}
